package cn.edu.scau.cmi.lishuoxin.interProgramming.experiment10.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import Hibernate.cn.edu.scau.cmi.lishuoxin.client.AlertBox;
import cn.edu.scau.cmi.lishuoxin.interProgramming.experiment10.domain.Orders;
import cn.edu.scau.cmi.lishuoxin.util.C3P0Utils;

public class OrdersDao {
	private AlertBox alert = new AlertBox();

	//添加订单
	public void insertOrder(Orders order) {
		try {
			// 1.获取核心类queryRunner,只要给连接池就好了，自动获取连接
			QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
			// 2.编写SQL语句
			String sql = "insert into orders values(?,?,?,?,?)";
			// 3.设置参数
			Object[] params = { order.getId(),order.getUser_id(),order.getNumber(),order.getCreatetime(),order.getNote() };
			// 4.执行sql语句
			int row = qr.update(sql, params);
			if (row > 0) {
				alert.display("添加订单成功！");
			} else {
				alert.display("添加订单失败！");
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	// 删除订单
	public void deleteOrder(int id) {
		try {
			QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
			String sql = "delete from orders where id = ?";
			int row = qr.update(sql, id);
			if (row > 0) {
				alert.display("删除订单成功！");
			} else {
				alert.display("删除订单失败！");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	// 查询订单
	public void selectOrderById(int id) {
		try {
			QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
			String sql = "select * from orders where id = ?";
			Orders order = qr.query(sql, id, new BeanHandler<Orders>(Orders.class));
			if (order != null) {
				alert.display(order.toString());
			} else {
				alert.display("查询失败！");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	// 修改订单
	public void updateOrder(Orders order) {
		try {
			QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
			String sql = "update orders set user_id=?,number=?,createtime=?,note=? where id=?";
			Object[] params = { order.getUser_id(),order.getNumber(),order.getCreatetime(),order.getNote(),order.getId()};
			int row = qr.update(sql, params);
			if (row > 0) {
				alert.display("修改订单成功！");
			} else {
				alert.display("修改订单失败！");
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}
